package com.hotelManager.www.service;

import com.hotelManager.www.dao.UserDao;
import com.hotelManager.www.dao.ShopDao;
import com.hotelManager.www.po.User;
import com.hotelManager.www.po.Shop;
import com.hotelManager.www.util.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class UserService {
    private final UserDao userDao = new UserDao();
    private final ShopDao shopDao = new ShopDao();

    Connection conn;

    {
        try {
            conn = JDBCUtils.getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 注册普通用户
    public boolean registerUser(User user) {
        try {
            return userDao.register(user, conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 注册商家用户（仅注册账号）
    public boolean registerMerchantUser(User user) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            System.out.println("商家用户注册失败：参数为空");
            return false;
        }

        if (!"merchant".equals(user.getRole())) {
            System.out.println("商家用户注册失败：角色不是merchant");
            return false;
        }

        try (Connection conn = JDBCUtils.getConnection()) {
            conn.setAutoCommit(false);
            System.out.println("开始注册商家用户：" + user.getUsername());

            // 1. 检查用户名是否已存在
            User existingUser = userDao.getUserByUsername(conn, user.getUsername());
            if (existingUser != null) {
                System.out.println("商家用户注册失败：用户名已存在");
                conn.rollback();
                return false;
            }

            // 2. 注册用户
            boolean userSuccess = userDao.register(user, conn);
            if (!userSuccess) {
                System.out.println("商家用户注册失败：数据库操作失败");
                conn.rollback();
                return false;
            }

            conn.commit();
            System.out.println("商家用户注册成功：" + user.getUsername());
            return true;
        } catch (SQLException e) {
            System.out.println("商家用户注册失败：" + e.getMessage());
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            System.out.println("商家用户注册失败：系统错误");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // 注册商家店铺（关联已注册的商家用户）
    public boolean registerMerchantShop(User user, Shop shop) {
        if (user == null || shop == null ||
                shop.getShopname() == null || shop.getAddress() == null || shop.getContact() == null) {
            System.out.println("商家店铺注册失败：参数为空");
            return false;
        }

        try (Connection conn = JDBCUtils.getConnection()) {
            conn.setAutoCommit(false);
            System.out.println("开始注册商家店铺：" + shop.getShopname());

            // 1. 获取商家用户ID
            User merchantUser = userDao.getUserByUsername(conn, user.getUsername());
            if (merchantUser == null) {
                System.out.println("商家店铺注册失败：商家用户不存在");
                conn.rollback();
                return false;
            }

            // 2. 检查是否已有店铺
            Shop existingShop = shopDao.findByUserId(merchantUser.getId());
            if (existingShop != null) {
                System.out.println("商家店铺注册失败：该商家已有店铺");
                conn.rollback();
                return false;
            }

            // 3. 设置店铺的user_id
            shop.setUserId(merchantUser.getId());

            // 4. 设置默认值
            shop.setAuditStatus("pending");
            shop.setSalesVolume(0);
            shop.setPublishTime(new java.util.Date());
            shop.setRevenue(new java.math.BigDecimal("0.00"));

            // 5. 创建店铺
            boolean shopSuccess = shopDao.Shopregister(shop, conn);
            if (!shopSuccess) {
                System.out.println("商家店铺注册失败：数据库操作失败");
                conn.rollback();
                return false;
            }

            conn.commit();
            System.out.println("商家店铺注册成功：" + shop.getShopname());
            return true;
        } catch (SQLException e) {
            System.out.println("商家店铺注册失败：" + e.getMessage());
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            System.out.println("商家店铺注册失败：系统错误");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    // 登录
    public User loginUser(String username, String password) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return userDao.login(conn, username, password);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    // 获取待审核充值的用户
    public List<User> getPendingRechargeUsers() throws Exception {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return userDao.findByRechargeStatus(conn, "pending");
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    // 通过充值申请
    public boolean approveRecharge(Integer userId) throws Exception {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);//开启事务

            User user = userDao.findById(userId); // Updated to match the new method signature
            if (user == null || !"pending".equals(user.getRechargeStatus())) {
                return false;
            }

            // 更新用户余额
            BigDecimal currentBalance = user.getBalance();
            BigDecimal rechargeAmount = user.getRechargeAmount();
            user.setBalance(currentBalance.add(rechargeAmount));
            user.setRechargeStatus("approved");
            user.setRechargeAmount(new BigDecimal(0));

            boolean success = userDao.update(conn, user);
            if (success) {
                conn.commit();
            } else {
                conn.rollback();
            }
            return success;
        } catch (Exception e) {
            if (conn != null) {
                conn.rollback();
            }
            throw e;
        } finally {
            if (conn != null) {
                conn.setAutoCommit(true);
                JDBCUtils.closeConnection(conn);
            }
        }
    }

    // 拒绝充值申请
    public boolean rejectRecharge(Integer userId) throws Exception {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            User user = userDao.findById(userId);
            if (user == null || !"pending".equals(user.getRechargeStatus())) {
                return false;
            }

            user.setRechargeStatus("rejected");
            user.setRechargeAmount(new BigDecimal(0));
            return userDao.update(conn, user);
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    // 
    public boolean recharge(User user, int amount) throws Exception {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            User currentUser = userDao.findById(user.getId());
            if (currentUser == null) {
                return false;
            }

            currentUser.setRechargeAmount(new BigDecimal(amount));
            currentUser.setRechargeStatus("pending");
            return userDao.update(conn, currentUser);
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    //修改信息
    public User getUserByUsername(String username) {
        try {
            return userDao.getUserByUsername(conn, username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 更新用户信息
    public boolean updateUser(User user) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            boolean success = userDao.updateUser(user, conn);
            if (success) {
                conn.commit();
            } else {
                conn.rollback();
            }
            return success;
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    public boolean updateUserPasswordOrUsername(User user) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            boolean success = userDao.updateUserPasswordOrUsername(conn,user);
            if (success) {
                conn.commit();
            } else {
                conn.rollback();
            }
            return success;
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }
    
    // 通过ID查找用户
    public User findById(Integer userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return userDao.findById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    // 根据角色获取用户
    public List<User> getUsersByRole(String role) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT * FROM users WHERE role = ?";
            List<User> users = new ArrayList<>();
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, role);
                try (ResultSet rs = stmt.executeQuery()) {
                    while (rs.next()) {
                        users.add(extractUserFromResultSet(rs));
                    }
                }
            }
            return users;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    // 根据多个角色获取用户
    public List<User> getUsersByRoles(List<String> roles) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            StringBuilder sql = new StringBuilder("SELECT id, username, balance, role, recharge_status, recharge_amount, status FROM users WHERE role IN (");
            for (int i = 0; i < roles.size(); i++) {
                sql.append("?");
                if (i < roles.size() - 1) {
                    sql.append(", ");
                }
            }
            sql.append(")");

            List<User> users = new ArrayList<>();
            try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
                for (int i = 0; i < roles.size(); i++) {
                    stmt.setString(i + 1, roles.get(i));
                }
                try (ResultSet rs = stmt.executeQuery()) {
                    while (rs.next()) {
                        User user = new User();
                        user.setId(rs.getInt("id"));
                        user.setUsername(rs.getString("username"));
                        user.setBalance(rs.getBigDecimal("balance"));
                        user.setRole(rs.getString("role"));
                        user.setRechargeStatus(rs.getString("recharge_status"));
                        user.setRechargeAmount(rs.getBigDecimal("recharge_amount"));
                        user.setStatus(rs.getString("status"));
                        users.add(user);
                    }
                }
            }
            return users;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    public boolean canMerchantLogin(Integer userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            Shop shop = shopDao.findByUserId(userId);
            if (shop == null) {
                return true; // 用户没有关联店铺，可以登录
            }
            String status = shop.getStatus();
            return !"banned".equals(status) && !"closed".equals(status);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    public boolean toggleUserStatus(Integer userId, String status) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            User user = userDao.findById(userId);
            if (user == null) {
                return false;
            }
            user.setStatus(status);
            return userDao.update(conn, user);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    private User extractUserFromResultSet(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setBalance(rs.getBigDecimal("balance"));
        user.setRole(rs.getString("role"));
        user.setRechargeStatus(rs.getString("recharge_status"));
        user.setRechargeAmount(rs.getBigDecimal("recharge_amount"));
        user.setStatus(rs.getString("status"));
        return user;
    }
}